package openones.samples.dataform.control;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import openones.samples.dataform.biz.DataFormBiz;
import openones.samples.dataform.entity.User;
import openones.samples.dataform.form.AddInForm;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;

import rocky.common.CommonUtil;
import rocky.common.Constant;
import rocky.mvcportlet.control.BaseControl;
import rocky.portlet.BaseOutForm;

public class AddControl extends BaseControl {
    private static final String K_MESSAGE = "MESSAGE";
    private static final String K_ERROR = "ERROR";
    private static final String DATE_FMT = "dd/MM/yyyy";
    static final Logger LOG = Logger.getLogger("AddControl");

    /**
     * Initial screen Add.
     */
    @Override
    public BaseOutForm init(RenderRequest request, RenderResponse response) throws PortletException, IOException {
        BaseOutForm outForm = new BaseOutForm();
        
        AddInForm initForm = new AddInForm();
        // Create data for initial screen Add. View default value of properties in AddInForm
        outForm.putRequest(AddInForm.FORM_BEAN, initForm);
        return outForm;
    }

    public BaseOutForm procAdd(ActionRequest request, Map<String, Object> reqMap, ActionResponse response)
            throws PortletException, IOException {
        LOG.debug("init.START");
        
        AddInForm form = new AddInForm();
        BaseOutForm outForm = new BaseOutForm();
        
        // Parse map of request into form bean
        form = (AddInForm) getData(reqMap, AddInForm.class);
        
        // Loggin
        LOG.debug("User name=:" + form.getUsername());
        LOG.debug("Birthday=:" + form.getBirthday());
        
        // Check validation: to be defined
        User userEntity = validate(form, outForm); 
        if (userEntity != null) {
            // Store the bean to database and return 
            new DataFormBiz().addUser(userEntity);
            outForm.putRequest(K_MESSAGE, "Save successfully.");
            
            // Save the form to re-display in the result screen.
            outForm.putRequest(AddInForm.FORM_BEAN, form);
        } else {
            outForm.putRequest(K_ERROR, "Data is not valid.");
        }
        
        LOG.debug("init.END");
        return outForm;
    }
    
    /**
     * Process List event.
     * @param request
     * @param reqMap
     * @param response
     * @return
     * @throws PortletException
     * @throws IOException
     */
    public BaseOutForm procList(ActionRequest request, Map<String, Object> reqMap, ActionResponse response)
    throws PortletException, IOException {
        DataFormBiz biz = new DataFormBiz();
        BaseOutForm outForm = new BaseOutForm();
        outForm.putRequest("USERS", biz.getUsers());
        
        return outForm;
    }
    
    /**
     * Simple data validation. It convert data form into entity if data is valid.
     * @param form
     * @return
     */
    User validate(AddInForm form, BaseOutForm outForm) {
        if (!CommonUtil.isNNandNB(form.getUsername())) {
            return null;
        }
        
        if (!CommonUtil.isNNandNB(form.getBirthday())) {
            return null;
        }
        
        Date birthday = CommonUtil.parse(form.getBirthday(), DATE_FMT); 
        if (birthday == null) {
            return null;
        }
        
        User user = new User();
        user.setUsername(form.getUsername());
        user.setBirthday(birthday);
        
        
        // debug upload filed
        LOG.debug(form.getAttachedFile());
        FileItem attachedFile = form.getAttachedFile(); 
        if (attachedFile != null) {
            LOG.debug("Attached file: " + attachedFile);
            try {
                // Create rootPath folder if it not existed.
                File rootPathFile = new File(form.getRootPath());
                if (!rootPathFile.exists()) {
                    if (!rootPathFile.mkdirs()) {
                        outForm.putRequest(K_ERROR, "Could not create folder '" + form.getRootPath() + "' on server.");
                    }
                }
                String filePath = attachedFile.getName();
                int lastSlashChar = attachedFile.getName().lastIndexOf("\\");
                String fileName = (lastSlashChar > 0) ? filePath.substring(lastSlashChar) : filePath;
                
                // Save attached file.
                attachedFile.write(new File(form.getRootPath() + File.separatorChar +  fileName));
                LOG.debug("Saved file '" + form.getRootPath() + File.separatorChar +  fileName + "'");
            } catch (Exception ex) {
                LOG.debug(ex);
            }
        }
        
        return user;
    }
    
    
}
